<template>
	<view class="main">
		<Loading v-if="firstLoading"></Loading>
		<view class="phone" v-else-if="isAuth">
			<view class="phone-content">
				<uv-icon name="checkmark-circle-fill" color="#47c9a2" size="150"></uv-icon>
				<view class="success-text">已实名</view>
			</view>
		</view>
		<view v-else>
			<view class="card m-10">
				<uv-form :model="formData" :rules="rules" ref="ruleForm">
					<uv-form-item label="姓名" prop="username">
						<uv-input v-model="formData.username" placeholder="请输入姓名" border="none">
						</uv-input>
					</uv-form-item>
					<uv-form-item label="身份证" prop="idcard">
						<uv-input v-model="formData.idcard" placeholder="请输入身份证" border="none">
						</uv-input>
					</uv-form-item>

				</uv-form>
				<view class="card flex p-b-10">
					<view class="wh-full center">
						<uv-upload :fileList="formData.fileList.img1" @afterRead="formData.fileList.afterRead"
							@delete="formData.fileList.deletePic" name="1" multiple :maxCount="1">
							<image src="/static/img/front.jpg" mode="widthFix" class="idImg" lazy-load observeLazyLoad>
							</image>
						</uv-upload>
						<view class="mp-10">人像面
							<view v-if="formData.fileList.imgValid1 && formData.fileList.img1.length == 0" class="red">
								请上传身份证人像面
							</view>
						</view>
					</view>
					<view class="wh-full center">
						<uv-upload :fileList="formData.fileList.img2" @afterRead="formData.fileList.afterRead"
							@delete="formData.fileList.deletePic" name="2" multiple :maxCount="1">
							<image src="/static/img/opposite.jpg" mode="widthFix" class="idImg" lazy-load
								observeLazyLoad>
							</image>
						</uv-upload>
						<view class="mp-10">国徽面
							<view v-if="formData.fileList.imgValid2 && formData.fileList.img2.length == 0" class="red">
								请上传身份证国徽面
							</view>
						</view>
					</view>
				</view>
			</view>
			<view>{{JSON.stringify(MetaInfo)}}</view>
			<view class="btn">
				<uv-button text="提交" @click="submit" :loading="loading" shape="circle"
					:color="app.globalData.primaryColor"></uv-button>
			</view>
		</view>
	</view>
</template>

<script setup>
	import {
		reactive,
		ref,
	} from "vue";
	import {
		onReady,
		onLoad,
		onShow
	} from '@dcloudio/uni-app'
	import config from '@/utils/config.js';
	const baseUrl = config.baseUrl
	const baseUrl2 = config.returnUrl

	const app = getApp()
	const firstLoading = ref(true)
	const showed = ref(false)
	const isAuth = ref(false)
	const formData = reactive({
		username: '',
		idcard: '',
		fileList: {
			img1: [],
			img2: [],
			imgValid1: false,
			imgValid2: false,
			// 删除图片
			deletePic(event) {
				formData.fileList[`img${event.name}`] = formData.fileList[`img${event.name}`].filter((item,
					index) => {
					return index != event.index
				})
				formData.fileList[`imgValid${event.name}`] = true
			},
			uploadFilePromise(url) {
				return new Promise((resolve, reject) => {
					app.uploadFile(url).then(res => {
						console.log(res)
						resolve(res?.url)
					})
				})
			},
			// 新增图片
			async afterRead(event) {
				// 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file)
				let fileListLen = formData.fileList[`img${event.name}`].length
				lists?.map((item) => {
					formData.fileList[`img${event.name}`].push({
						...item,
						status: '',
						message: '上传中'
					})
				})
				// 此写法可以避免使用老写法在VUE3中不更新
				// #ifdef VUE3
				formData.fileList[`img${event.name}`] = formData.fileList[`img${event.name}`].filter((item,
					index, status) => {
					status = 'success'
					return index >= 0
				})
				formData.fileList[`imgValid${event.name}`] = false
				// #endif
				for (let i = 0; i < lists.length; i++) {
					const url = await formData.fileList.uploadFilePromise(lists[i].url)
					console.log(url, 'url');
					let item = formData.fileList[`img${event.name}`][fileListLen]
					formData.fileList[`img${event.name}`].splice(fileListLen, 1, Object.assign(item, {
						code: 'success',
						status: 'success',
						message: '',
						url: url
					}))
					fileListLen++
				}
			},
		}
	})
	const nameLengthValidator = (_, val) => {
		return val?.length > 1
	}



	function isIdCard(_, val) {
		const reg_IDRe18 =
			/^([1-6][1-9]|50)\d{4}(18|19|20)\d{2}((0[1-9])|10|11|12)(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/;
		const reg_IDre15 = /^([1-6][1-9]|50)\d{4}\d{2}((0[1-9])|10|11|12)(([0-2][1-9])|10|20|30|31)\d{3}$/;
		return reg_IDRe18.test(val.replace(/\s*/g, "")) || reg_IDre15.test(val.replace(/\s*/g, ""))
	}

	const rules = reactive({
		username: [{
				type: 'string',
				required: true,
				message: '请填写姓名',
				trigger: ['blur', 'change']
			},
			{
				message: '至少两个字符',
				validator: nameLengthValidator,
				trigger: ['blur', 'change']
			}
		],
		idcard: [{
				required: true,
				message: '请填写身份证号',
				trigger: ['blur', 'change']
			},
			{
				validator: isIdCard,
				message: '身份证号格式不正确',
				trigger: ['blur', 'change']
			},
		],

	})
	const checkUser = () => {
		firstLoading.value = true
		showed.value = false
		app.post('api.auth.center/isRealPerson').then(res => {
			isAuth.value = res.is_realperson
			firstLoading.value = false
			if (res.is_realperson) {
				toResults()
			}
		}).catch(err => {
			console.log(err);
			firstLoading.value = false
		})
	}
	const order_no = ref(null)
	onLoad((e) => {
		order_no.value = e?.order_no
		checkUser()
	})
	onShow(() => {
		showed.value && checkUser()
	})
	const ruleForm = ref(null)
	const idCardvalid = () => {
		let isValid = true
		for (let index = 1; index <= 2; index++) {
			formData.fileList[`imgValid${index}`] = true
			if (formData.fileList[`img${index}`].length == 0) {
				isValid = false
			}
		}
		return isValid
	}
	const loading = ref(false)
	const submit = () => {
		app.vibrate()
		const isValid = idCardvalid()
		ruleForm.value.validate().then(() => {
			// if (!isValid) {
			// 	return
			// }
			loading.value = true
			const {
				username,
				idcard,
				fileList
			} = formData
			let returnUrl = "";
			if (order_no.value) {
				returnUrl = baseUrl2 + "/#/pages/results/results?order_no=" + order_no.value +
					"&sourcePath=realperson"
			} else {
				returnUrl = baseUrl2 + "/#/pages/my/my"
			}
			const data = {
				username,
				idcard,
				metaInfo: JSON.stringify(window.getMetaInfo()),
				completeuseridimg: fileList.img1[0].url,
				completeuseridfimg: fileList.img2[0].url,
				returnUrl: returnUrl
			}
			// console.log(data)
			// uni.setStorageSync('realperson', data)
			app.post('api.auth.center/newrealpersion', data).then(res => {
				console.log(res.signUrl)
				let url = res.signUrl
				window.location.href = url
				// showed.value = true
				// loading.value = false
				// isAuth.value = true
				// order_no.value && uni.navigateBack()
				// toResults()
			}).catch(error => {
				loading.value = false
			})
		}).catch(errors => {
			loading.value = false
		})
	}
	const toResults = () => {
		order_no.value && uni.redirectTo({
			url: '/pages/results/results?order_no=' + order_no.value,
		})
	}
</script>

<style lang="scss" scoped>
	.main {
		height: -webkit-fill-available;
		width: -webkit-fill-available;
		position: absolute;
	}

	.p-b-10 {
		padding-bottom: 10px;
	}

	.card {
		background-color: white;
		justify-content: center;
		min-height: 100px;

		.cardTitle {
			font-size: medium;
			font-weight: 600;
			padding: 10px;
			display: flex;
			justify-content: space-between;
			align-items: center;

			.cardExtra {
				color: #999;
				font-size: 12px;
			}
		}

		.center {
			text-align: center;
			margin-top: 10px;
		}

		.mp-10 {
			margin-top: 10px;
		}

		::v-deep {

			uv-upload,
			.uv-upload {
				width: 100% !important;
				height: 100% !important;
			}

			.uv-upload__wrap {
				justify-content: center;
			}

			.uv-upload__wrap__preview {
				margin: 0 !important;
			}

			.idImg,
			.uv-upload__wrap__preview__image {
				width: 160px !important;
				height: 130px !important;
			}
		}
	}

	::v-deep .uv-form {
		display: grid;
		background-color: transparent;

		.uv-form-item {
			background-color: white;
			border-radius: var(--nut-cell-border-radius, 6px);

			.uv-form-item__body {
				padding: 10px;

				.nut-input {
					padding: 0 0 0 5px !important;
					border: none !important;

					.uni-input-placeholder {
						color: rgb(192, 196, 204);
					}
				}

				.uv-form-item__body__left {
					flex: none !important;
					width: var(--nut-form-item-label-width, 90px) !important;
					margin-right: var(--nut-form-item-label-margin-right, 10px);
					font-size: var(--nut-form-item-label-font-size, 14px);
					font-weight: normal;
					text-align: var(--nut-form-item-label-text-align, left);
					word-wrap: break-word;
				}

				.uv-form-item__body__right {
					background-color: whitesmoke;
					border-radius: 10px;
					color: black;
					padding: 4px;
					min-height: 30px;

					.uv-input__content__field-wrapper__field {
						color: inherit !important;
					}

					.uv-textarea {
						background-color: transparent !important;
					}
				}
			}

			.uv-form-item__body__right__message {
				margin-left: var(--nut-form-item-label-width+25px, 90px+25px) !important;
			}
		}

		.uv-textarea {
			padding: 0;
			margin: 0 4px;
		}
	}

	.placeholder {
		color: rgb(192, 196, 204);
	}

	.default {
		color: rgb(48, 49, 51);
	}

	.red {
		font-size: 12px;
		color: #f56c6c;
	}

	.input {
		width: -webkit-fill-available;
		height: 24px;
		min-height: 1.4em;
		margin: 0 4px;
		overflow: hidden;
		font-size: 14px;
		text-align: left;
		display: flex;
		align-items: center;
		justify-content: space-between;
	}

	::v-deep .nut-cell-group__wrap {
		gap: 10px;
		display: grid;
		background-color: transparent;

		.nut-form-item {
			border-radius: var(--nut-cell-border-radius, 6px);
		}
	}

	/* Phone */
	.phone {
		width: -webkit-fill-available;
		padding: 20px;
		background-color: inherit;
		border-radius: 10px;
		display: flex;
		flex-direction: column;

		.phone-content {
			display: flex;
			flex-direction: column;
			justify-content: center;
			align-items: center;
			margin: auto;
			text-align: center;
			width: 70%;
			gap: 10px;

			::v-deep.nut-icon {
				position: relative;
				border-radius: 100%;
				width: 150px !important;
				height: 150px !important;
				background: #47c9a2;
				color: #e2feee;
				margin: auto;
				font-size: -webkit-xxx-large;
			}
		}
	}
</style>